#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>
#include <sys/wait.h>

int main(void){
	int p2c[2];
	int c2p[2];

	if (pipe(p2c) == -1){
		perror("create p2c failed");
		exit(-1);
	}
	if (pipe(c2p) == -1){
		perror("create c2p failed");
		exit(-1);
	}

	char received_str[100];
	memset(received_str, 0, 100);
	if (fork() > 0){
		// parent
		close(p2c[0]);
		char* parent_input = "Hi, This is Parent Process";
		write(p2c[1], parent_input, strlen(parent_input));
		close(p2c[1]);
		close(c2p[1]);
		// Wait for child to send a string
		wait(NULL);
		printf("wait end\n");
		read(c2p[0], received_str, 100);
		printf("Parent Received: %s\n", received_str);
		close(c2p[0]);
	}else{
		// child
		close(c2p[0]);
		close(p2c[1]);
		read(p2c[0], received_str, 100);
		printf("Child Received: %s\n", received_str);
		close(p2c[0]);
		char* child_input = "Hi, This is child process";
		write(c2p[1], child_input, strlen(child_input));
		close(c2p[1]);
		printf("Child Process Exist\n");
	}
}
